import os
import json

def write_dependency(dependency_dist, bundle_name,deps):
    components_defs = deps['components']
    third_party_defs = deps['third_party']
    for c_def in components_defs:
        if c_def in dependency_dist :
            dependency_dist[c_def].append(bundle_name)
        else:
            dependency_dist[c_def] = [bundle_name]
    for t_def in third_party_defs:
        if t_def in dependency_dist :
            dependency_dist[t_def].append(bundle_name)
        else:
            dependency_dist[t_def] = [bundle_name]


def run (path):
    # 存储依赖关系dist
    dependency_dist = {}
    # 遍历目录下的所有文件和子目录
    for root, dirs, files in os.walk(path):
        for file in files:
            if file == 'bundle.json':
                # 构建完整的文件路径
                file_path = os.path.join(root, file)
                # 读取 JSON 文件并转换为 Python 对象
                with open(file_path, 'r') as f:
                    json_data = json.load(f)
                    bundle_name = json_data['name'].split('/')[-1]
                    deps = json_data['component']['deps']
                    # 处理 json_data写入dependency_dist
                    write_dependency(dependency_dist, bundle_name,deps)
    dependency_file_path = 'dependency_table.json'
    # 判断文件是否存在
    if not os.path.exists(dependency_file_path):
        # 如果文件不存在，则创建文件并写入 JSON 数据
        with open(dependency_file_path, 'w') as f:
            json.dump(dependency_dist, f,indent=4)


if __name__ == '__main__':
    run('../')